//
//  MenuCollectionViewCell_PageBase.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2020/10/9.
//  Copyright © 2020 moon. All rights reserved.
//

#import "MenuCollectionViewCell_PageBase.h"

@implementation MenuCollectionViewCell_PageBase
- (id)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        self.contentView.layer.cornerRadius = 5;
        self.contentView.layer.borderColor = [UIColor systemGrayColor].CGColor;
        self.contentView.layer.borderWidth = 1;
        self.lineView = [[UIView alloc] init];
        self.lineView.backgroundColor = [UIColor systemBlueColor];
        [self.contentView addSubview:self.lineView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.contentView.bounds;
    MKUICollectionViewPageFlowLayout *pageLayout = self.collectionCellModel.collectionView.mk_collectionViewPageFlowLayout;
    if(pageLayout&&pageLayout.pagingEnabled){
        MKCGAxis X = pageLayout.scrollAxis;
        CGRect f1 = bounds;
        MKCGRectSetLength(&f1, X, 1);
        MKCGRectSetMin(&f1, X, MKCGRectGetLength(bounds, X)*pageLayout.pagingCellPosition);
        self.lineView.frame = f1;
    }
}
- (void)setCollectionCellModel:(__kindof MKUICollectionViewCellModel *)collectionCellModel{
    [super setCollectionCellModel:collectionCellModel];
    MKUICollectionViewPageFlowLayout *pageLayout = self.collectionCellModel.collectionView.mk_collectionViewPageFlowLayout;
    self.lineView.hidden = !(pageLayout&&pageLayout.pagingEnabled);
    [self.lineView.superview bringSubviewToFront:self.lineView];
//    id modelValue = self.collectionCellModel.modelValue;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCellModel:(__kindof MKUICollectionViewCellModel *)cellModel{
    Menu *modelObject = cellModel.modelValue;
    if(!modelObject.icon&&modelObject.iconUrl.length!=0){//异步加载图片
        @MK_WEAKIFY(self);
        @MK_WEAKIFY(cellModel);
        [modelObject getIconWithCompletion:^(UIImage * _Nonnull image, NSError * _Nonnull error) {
            @MK_NORMALIZE(self);
            @MK_NORMALIZE(cellModel);
            if(image&&self.collectionCellModel==cellModel){//异步完成之后，需要判断是否还是上一个单元格
                [self.collectionCellModel refresh];
            }
        }];
    }
}
@end
